package sword;

/**
 * 问题：输入一个整数，输出该数二进制表示中1的个数。其中负数用补码表示。<br>
 * 提示：在计算机内存中负数就是用补码表示的，所以不用去思考将负数转换成补码的过程
 *
 * @author longzj
 */
public class CountNumber {

    public static void main(String[] args) {
        CountNumber number = new CountNumber();
        System.out.println("result = " + number.numberOf1(-1));
    }


    private int numberOf1(int n) {
        int count = 0;
        String s = Integer.toBinaryString(n);
        if (n < 0) {
            char[] chs = new char[Integer.SIZE];
            for (int i = 0; i < Integer.SIZE; i++) {
                chs[Integer.SIZE - 1 - i] = (char) (((n >> i) & 1) + '0');
            }
            s = new String(chs);
        }
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (c == '1') {
                count += 1;
            }
        }
        return count;
    }

}
